package com.hao.epidemic_prevention.security.adminlogin;

import com.hao.epidemic_prevention.bean.Admin;
import com.hao.epidemic_prevention.dao.AdminMapper;
import com.hao.epidemic_prevention.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AdminServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminService adminService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("登录用户名: " + username);

        Admin admin = adminMapper.getAdminByUsername(username);

        if(admin == null) {
            logger.error("用户名不存在");
            throw new UsernameNotFoundException("用户名不存在");
        }
        else {

            String authorities = "ROLE_ADMIN";
            List<SimpleGrantedAuthority> roles = new ArrayList<>();
            roles.add(new SimpleGrantedAuthority(authorities));

            User result = new User(admin.getUsername(), admin.getPassword(), roles);
            logger.info("查找用户成功: " + admin.getUsername());

            return result;
        }

    }
}
